/**
* 票务记录
*/
import React, { Component } from 'react'

import {
  Platform,
  StyleSheet,
  Text,
  View,
  Image,
  Alert,
  Button,
  Dimensions,
  TouchableHighlight,
  TouchableOpacity,
  StatusBar,
  Linking,
  FlatList,
  ActivityIndicator
} from 'react-native'

import NavPage from '../../common/NavPage'
import SafeView from 'react-native-safe-area-view'
import ImageResources from '../../common/ImageResources'
import FetchResources from '../../common/FetchResources'
import RNToAndroid from '../../common/RNToAndroid'
import TicketingItem from './TicketingItem';
import qs from 'qs'
import axios from 'axios'
import Toast from 'antd-mobile/lib/toast'
import { RouteHelper } from 'react-navigation-easy-helper'
import GetSetStorge from '../../common/GetSetStorge'
import screen from '../../common/screen'

let checkPageIndex = 1
let orderPageIndex = 1
export default class Customer extends Component {
  static navigationOptions = ({ navigation }) => ({
    tabBarOnPress: (tab) => {
      navigation.state.params.navigatePress()
      tab.jumpToIndex(tab.scene.index)
    }
  })

  constructor(props) {
    super(props);
    this.state = {
      showFoot:0,
      showFoot1:0,
      dataSource:[],
      checkTicketDataSource:[],
      isLoading:true,
      user:'',
      activeIndex:0,
      checkJump:true
    }
  }

  componentDidMount() {

    GetSetStorge.getStorgeAsync('loginInfo').then((result) => {
      if (result) {

        axios.post(FetchResources.Fetch.GetPermission,//获取当天权限和项目价格
          qs.stringify({
            sellerId:result.split('|')[0],
          })
        ).then((response) => {
          if(response.data.success){//登录成功
            let list = response.data.permissionList
            let inspectList = []
            if(list.length >= 1){
              for(let i=0 ; i<list.length ; i++){
                if(list[i]['checkPermission'] == '1'){ //该用户对这个项目具有验票权限
                  inspectList.push(list[i])
                }
              }
              if(JSON.stringify(inspectList) == '[]'){ // 没有验票权限 
                this.setState({user:result.split('|')[0],checkJump:false},()=>{
                  this.orderListData()
                })
                return 
              }
              if(inspectList.length >= 1){
                this.setState({user:result.split('|')[0],checkJump:true},()=>{
                  this.orderListData()
                  this.checkTicketData()
                })
              }
            }else{
              this.setState({user:result.split('|')[0],checkJump:false},()=>{
                this.orderListData()
              })
              return 
            }

          }
    
        }).catch((error) => {
          // alert(JSON.stringify(error))
          Toast.hide()
        })

        
      }
    }).catch((error) => {
      console.log('==========================')
      console.log('系统异常' + error)
      console.log('==========================')
    })
  }

  goBack() {
    RouteHelper.pop()
  }

  // tab 切换调用方法
  clickTabCallback = () => {
    // this.refs.header.reload()
  }

  show(){

  }

	checkTicketData() {
		if(checkPageIndex === 1){
			Toast.loading('正在加载...', 0)
		}
    let { user } = this.state
		axios.post(FetchResources.Fetch.CheckList,//验票记录接口
			qs.stringify({
				checkUser:user,//验票员ID
				pageNo: checkPageIndex,//页数
				pageSize: 10,//每页记录数
				
			})
		).then(response => {
			Toast.hide()
      let foot = 0
      // alert(response.data.rows.length)
      if(response.data.success){
        if (response.data.rows.length < 10) {
          foot = 1
        }
        if (checkPageIndex === 1) {
          this.setState({
            checkTicketDataSource: response.data.rows,
            isLoading: false,
            showFoot1: foot,
          })
          return
        }
        this.setState({
          checkTicketDataSource: this.state.checkTicketDataSource.concat(response.data.rows),
          isLoading: false,
          showFoot1: foot,
        })

      
      }else{

      }

		}).catch((error) => {
			console.log(error)
			Toast.hide()
			this.setState({
				error: true
			})
		})
	}


  orderListData(){
    let {user} = this.state
    if(orderPageIndex === 1){
			Toast.loading('正在加载...', 0)
		}
		axios.post(FetchResources.Fetch.OrderList, ////售票订单接口
			qs.stringify({
				createUser:user,//售票员ID
				pageNo: orderPageIndex,//页数
				pageSize: 10,//每页记录数
				
			})
		).then(response => {
			Toast.hide()
      let foot = 0
      // alert(response.data)
      if(response.data.success){
        if (response.data.rows.length < 10) {
          foot = 1
        }
        if (orderPageIndex === 1) {
          this.setState({
            dataSource: response.data.rows,
            isLoading: false,
            showFoot: foot,
          })
          return
        }
        this.setState({
          dataSource: this.state.dataSource.concat(response.data.rows),
          isLoading: false,
          showFoot: foot,
        },()=>{
        })
      
      }else{

      }

		}).catch((error) => {
			console.log(error)
			Toast.hide()
			this.setState({
				error: true
			})
		})
  }

  _orderListRenderItem = ({ item }) => (
		<TicketingItem
      singlePrice={item.singlePrice}
			leftNum={item.leftNum}
			orderTime={item.orderTime}
			checkTime={item.checkTime}
			totalPrice={item.totalPrice}
			num={item.num}
			consumptionName={item.consumptionName}
			ticketSource={item.ticketSource}
			state={item.state}
			ticketName={item.ticketName}
		/>
  )

  _checkTicketRenderItem = ({ item }) => (
		<TicketingItem
      singlePrice={item.singlePrice}
			leftNum={item.leftNum}
			orderTime={item.orderTime}
			checkTime={item.checkTime}
			totalPrice={item.totalPrice}
			num={item.num}
			consumptionName={item.consumptionName}
			ticketSource={item.ticketSource}
			state={item.state}
			ticketName={item.ticketName}
		/>
  )
  
  _orderListOnEndReached() {
		//如果是正在加载中或没有更多数据了，则返回
		if (this.state.showFoot != 0) {
			return
		}
		orderPageIndex++
		//底部显示正在加载更多数据
		this.setState({ showFoot: 2 })
		//获取数据
		this.orderListData()
  }

  _checkTicketOnEndReached(){
		//如果是正在加载中或没有更多数据了，则返回
		if (this.state.showFoot1 != 0) {
			return
		}
		checkPageIndex++
		//底部显示正在加载更多数据
		this.setState({ showFoot: 2 })
		//获取数据
		this.checkTicketData()
  }


  _checkTicketRenderFooter() {
		let { showFoot1 } = this.state
		if (showFoot1 === 1) {
			return (
				<View>
					{
						this.state.pageData == 0 ?
							<View style={{ height: 30, alignItems: 'center', justifyContent: 'flex-start', }}>
								<Text style={{ color: '#999999', fontSize: 14, marginTop: 5, marginBottom: 5, textAlign:'center' }}>
									没有更多数据了
              </Text>
							</View>
							:
							<View style={styles.footerImage}>
                <Text style={{ color: '#999999', fontSize: 14, marginTop: 5, marginBottom: 5, textAlign:'center'}}>
									没有更多数据了
                </Text>
								{/* <Image source={ImageResources.MyOrderIcon.OrderBottomText} /> */}
							</View>
					}
				</View>
			)
		} else if (showFoot1 === 2) {
			return (
				<View style={styles.footer}>
					<ActivityIndicator color='#105eae'
						size="small" />
					<Text>正在加载更多数据...</Text>
				</View>
			)
		} else if (showFoot1 === 0) {
			return (
				<View style={styles.footer}>
					<Text></Text>
				</View>
			)
		}
  }


  _orderListRenderFooter() {
		let { showFoot } = this.state
		if (showFoot === 1) {
			return (
				<View>
					{
						this.state.pageData == 0 ?
							<View style={{ height: 30, alignItems: 'center', justifyContent: 'flex-start', }}>
								<Text style={{ color: '#999999', fontSize: 14, marginTop: 5, marginBottom: 5, textAlign:'center' }}>
									没有更多数据了
              </Text>
							</View>
							:
							<View style={styles.footerImage}>
                <Text style={{ color: '#999999', fontSize: 14, marginTop: 5, marginBottom: 5, textAlign:'center'}}>
									没有更多数据了
                </Text>
								{/* <Image source={ImageResources.MyOrderIcon.OrderBottomText} /> */}
							</View>
					}
				</View>
			)
		} else if (showFoot === 2) {
			return (
				<View style={styles.footer}>
					<ActivityIndicator color='#105eae'
						size="small" />
					<Text>正在加载更多数据...</Text>
				</View>
			)
		} else if (showFoot === 0) {
			return (
				<View style={styles.footer}>
					<Text></Text>
				</View>
			)
		}
  }
  

  
  onButtonPress() {
    // Linking.openURL('tel:4009646567')
    // RNToAndroid.startActivityFromJS('com.ylxapp.udesk.activity.UdeskInitKeyActivity','客服');

  }

  render() {
    let {dataSource,activeIndex,checkTicketDataSource,checkJump} = this.state
    return (
      <SafeView forceInset={{ top: 'always', bottom: 'never' }} style={{flex: 1 }}>
        <View style={styles.container}>
          <NavPage goBack={this.goBack.bind(this)} showGoBack={true} bgColor={'#F6F7F8'} />
          <StatusBar
            animated={true}
            hidden={false}
            backgroundColor={'transparent'}
            translucent={true}
            barStyle={'default'}
            showHideTransition={'fade'}
            networkActivityIndicatorVisible={true}
          />

          <View style={{height:72,paddingBottom:6}}>
            <View style={{flex:1,flexDirection:'row',alignItems:'center'}} >
              <Text style={{flex:3,fontSize:24,fontWeight:'500',color:'#111',paddingLeft:30}}>票务记录</Text>
              <View style={{flex:1.5,flexDirection:'row',paddingRight:10}} >
                <Text style={[activeIndex === 0 ? {fontWeight:'500',color:'#111'}:null,{flex:1,fontSize:18}]} onPress={()=>{this.setState({activeIndex:0})}}>售票</Text>
                <Text style={[activeIndex === 1 ? {fontWeight:'500',color:'#111'}:null,{flex:1,fontSize:18}]} onPress={()=>{this.setState({activeIndex:1})}}>验票</Text>
              </View>
            </View>

            {/* <View style={{paddingLeft:40,flexDirection:'row',alignItems:'center'}}>
              <TouchableOpacity onPress={this.show.bind(this)}  activeOpacity={1} style={{flexDirection:'row',alignItems:'flex-end'}} >
                <Text style={{fontSize:14,color:'#5C7094'}}>卡丁车</Text><Image source={ImageResources.CommonIcon.Down} style={styles.img} />
              </TouchableOpacity>
              <TouchableOpacity onPress={this.show.bind(this)}  activeOpacity={1} style={{flexDirection:'row',alignItems:'flex-end',marginLeft:20}} >
                <Text style={{fontSize:14,}}>今天</Text><Image source={ImageResources.CommonIcon.Down} style={styles.img} />
              </TouchableOpacity>
            </View> */}

          </View>

          <View style={{marginBottom:12,}}>
          {
            activeIndex === 0 ?
          
            <FlatList
              data={dataSource}
              renderItem={this._orderListRenderItem}
              ListFooterComponent={this._orderListRenderFooter.bind(this)}
              onEndReached={this._orderListOnEndReached.bind(this)}
              onEndReachedThreshold={1}
              showsVerticalScrollIndicator={false}    // 隐藏垂直指示器
            />:
            (
              activeIndex === 1 && checkJump ?
              <FlatList
                data={checkTicketDataSource}
                renderItem={this._checkTicketRenderItem}
                ListFooterComponent={this._checkTicketRenderFooter.bind(this)}
                onEndReached={this._checkTicketOnEndReached.bind(this)}
                onEndReachedThreshold={1}
                showsVerticalScrollIndicator={false}    // 隐藏垂直指示器
              />:
              <View style={{flex:1,flexDirection:'row',alignItems:'center',justifyContent: 'center',width:screen.width,marginTop:100}} >
                <Text style={{fontSize:24,fontWeight:'500',color:'#111',textAlign:'center'}}>没有验票权限</Text>
              </View>
            )
          }
          </View>
        </View>
      </SafeView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F6F7F8',
  },
  header: {
    height: 500
  },
  customerImage: {
    flex: 1.5,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  customerImageSize: {
    height: 102,
    width: 132,
    resizeMode: "contain"
  },
  bottomButton: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'flex-end',
    marginBottom: 25,
  },
  TouchableHighlightStyle: {
    borderRadius: 6,
    marginTop: 5,
    padding: 13,
    alignItems: 'center',
    width: Dimensions.get('window').width * 0.85,
    backgroundColor: "#105eae"
  },
  buttonText: {
    fontSize: 16,
    alignItems: 'center',
    textAlign: "center",
    color: "#fff"
  },
  img:{
    width:15,
    height:15,
  }
});